package spese.gestore.androidiani;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.ImageButton;

/**
 * Questa classe implementa l'interfaccia per la cattura di un'immagine
 * all'interno dell'activity. Quando viene scattata l'immagine si viene subito
 * inviati all'Activity della Nuova Missione.
 * 
 * @author Fusinato Lorenzo - Androidiani
 * 
 */
public class Take_Photo extends Activity implements SurfaceHolder.Callback {

	private SurfaceView mSurfaceView;
	private SurfaceHolder mSurfaceHolder;
	private Camera mCamera;
	private boolean mPreviewRunning;
	public String missione;
	public int mDay;
	public int mMonth;
	public int mYear;
	public int mHour;
	public int mMinute;
	public String nameFile;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		final Calendar cal = Calendar.getInstance();
		mYear = cal.get(Calendar.YEAR);
		mMonth = cal.get(Calendar.MONTH);
		mDay = cal.get(Calendar.DAY_OF_MONTH);
		mHour = cal.get(Calendar.HOUR_OF_DAY);
		mMinute = cal.get(Calendar.MINUTE);

		Intent intent = getIntent();
		// ottengo i dati proveninienti dall'activity chiamante

		missione = intent.getStringExtra("riga missione");

		getWindow().setFormat(PixelFormat.TRANSLUCENT); // aggiungo il
														// traslucido
		requestWindowFeature(Window.FEATURE_NO_TITLE); // no barra titolo
		// Full Screen
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.layout_take_photo);

		ImageButton buttonPicture = (ImageButton) findViewById(R.id.camera_surface_button);

		buttonPicture.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mCamera.takePicture(null, null, jpegCallback);
			}
		});

		mSurfaceView = (SurfaceView) findViewById(R.id.camera_surface);
		mSurfaceHolder = mSurfaceView.getHolder(); // recupero l'holder della
													// surfaceview
		mSurfaceHolder.addCallback(this); // faccio la bind alla nostra activity
		mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); // tipo
																			// di
																			// surface,
																			// suggerito
																			// nei
																			// tutorial
																			// ufficiali
	}

	PictureCallback jpegCallback = new PictureCallback() {
		public void onPictureTaken(byte[] _data, Camera _camera) {

			// File sdImageMainDirectory = new File("/sdcard");
			String imgext = new String("/gestore_spese/"+missione+"/");
			File root = Environment.getExternalStorageDirectory();
			File img1 = new File(root, imgext);

			nameFile = ("img" + "_" + missione + "_" + mDay + "_" + mMonth
					+ "_" + mYear + "_" + mHour + "_" + mMinute + ".jpg");

			// String nameFile = "capturedpic.jpg";
			File img = new File(img1, nameFile);

			try {
				img1.mkdirs(); // creo directory per salvare il file

				Bitmap myImage = BitmapFactory.decodeByteArray(_data, 0,
						_data.length);

				FileOutputStream fileOutputStream = new FileOutputStream(img);

				BufferedOutputStream bos = new BufferedOutputStream(
						fileOutputStream);

				myImage.compress(CompressFormat.JPEG, 100, bos);

				bos.flush();
				bos.close();

				// BitmapFactory.Options options=new BitmapFactory.Options();
				// options.inSampleSize = 1;

			} catch (FileNotFoundException e) {
				Log.e("demo", e.toString());
				mCamera.release();
			} catch (IOException e) {
				e.printStackTrace();
				mCamera.release();
			}

			// riparte la preview della camera
			// mCamera.startPreview();

			String root_img = img.toString();
			String array[] = {missione,root_img,"not_from_intent","1"};
			System.out.println("Voglio vedere cosa mi da di root= "+img);
			Intent intent = new Intent(Take_Photo.this, Nuova_Spesa.class);
			intent.putExtra("array",array);
			startActivity(intent);
			

		}
	};

	/**
	 * Classe per capire cosa succede al cambio dell'interfaccia, come ad es
	 * quando si fa la foto
	 * 
	 * @see android.view.SurfaceHolder.Callback#surfaceChanged(android.view.SurfaceHolder,
	 *      int, int, int)
	 */
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		if (mPreviewRunning)
			mCamera.stopPreview();

		// setto le preferenze
		Camera.Parameters p = mCamera.getParameters(); // prendo le preferenze
														// della camera

		// recupero le risoluzioni supportate dalla camera
		p.setPreviewSize(p.getPreviewSize().width, p.getPreviewSize().height);
		p.setPictureSize(p.getPictureSize().width, p.getPictureSize().height);

		ArrayList<Size> list = (ArrayList<Size>) p.getSupportedPictureSizes();
		int picture_width = list.get(list.size() - 1).width;
		int picture_height = list.get(list.size() - 1).height;
		p.setPictureSize(picture_width, picture_height); // setto la camera alla
															// risoluzione più
															// bassa
		p.setJpegQuality(80); // qualità compressione JPEG

		mCamera.setDisplayOrientation(90);

		/* salvo le pref */
		mCamera.setParameters(p);
		try {
			/* lancio la preview */
			mCamera.setPreviewDisplay(arg0);
			mCamera.startPreview();
			mPreviewRunning = true;
		} catch (IOException e) {
			mCamera.release();
			mCamera = null;
		}

	}

	/**
	 * Crea l'intererfaccia della fotocamera
	 * 
	 * @see android.view.SurfaceHolder.Callback#surfaceCreated(android.view.SurfaceHolder)
	 */
	public void surfaceCreated(SurfaceHolder holder) {
		mCamera = Camera.open();

	}

	/**
	 * Distrugge l'interfaccia della fotocamera all'interno della mia app
	 * 
	 * @see android.view.SurfaceHolder.Callback#surfaceDestroyed(android.view.SurfaceHolder)
	 */
	public void surfaceDestroyed(SurfaceHolder holder) {
		mCamera.stopPreview();
		mPreviewRunning = false;
		mCamera.release();
	}

	/**
	 * Con questo metodo impongo al device che al tasto "back" torni alla lista
	 * spese ripassando i parametri adeguati.
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			Intent intent = new Intent(Take_Photo.this, Lista_Spese.class);
			intent.putExtra("riga missione", missione);
			startActivity(intent);
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}
}